package com.fzu.normalservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fzu.commonutil.entity.Image;
import com.fzu.commonutil.mapper.ImageMapper;
import com.fzu.commonutil.util.CodeEnum;
import com.fzu.normalservice.service.ImageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zyq
 * @since 2023-03-26
 */
@Service
public class ImageServiceImpl extends ServiceImpl<ImageMapper, Image> implements ImageService {

    @Override
    public void operateHouseKeeperImage(Integer housekeeperId, List<String> imageUrlList) {
        // 删除旧的关联关系
        LambdaQueryWrapper<Image> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Image::getSuperId, housekeeperId);
        wrapper.eq(Image::getType, CodeEnum.HOUSEKEEPER.getCode());
        List<Image> list = super.list(wrapper);
        if (!CollectionUtils.isEmpty(list)) {
            Set<Integer> ids = list.stream().map(Image::getId).collect(Collectors.toSet());
            super.removeByIds(ids);
        }
        // 添加新的关联关系
        List<Image> entityList = new ArrayList<>();
        for (String url : imageUrlList) {
            entityList.add(new Image().setUrl(url).setSuperId(housekeeperId).setType(CodeEnum.HOUSEKEEPER.getCode()));
        }
        super.saveBatch(entityList);
    }

    @Override
    public List<String> listByHouseKeeperId(Integer superId) {
        LambdaQueryWrapper<Image> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Image::getSuperId, superId);
        wrapper.eq(Image::getType, CodeEnum.HOUSEKEEPER.getCode());
        List<Image> list = super.list(wrapper);
        return list.stream().map(Image::getUrl).collect(Collectors.toList());
    }

    @Override
    public String getServiceTypeUrl(Integer serviceTypeId) {
        LambdaQueryWrapper<Image> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Image::getSuperId, serviceTypeId);
        wrapper.eq(Image::getType, CodeEnum.SERVICE_TYPE.getCode());
        List<Image> list = super.list(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            return "";
        } else {
            return list.get(0).getUrl();
        }
    }
}
